package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.pojo.DtsStorage;
import com.qf.service.DtsStorageService;
import com.qf.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wanghaotian
 * time:2022/12/20,0020 13:55
 * description:
 */

@RestController
@CrossOrigin("*")
@RequestMapping("/admin/storage")
public class StorageController {

    @Autowired
    private DtsStorageService storageService;

    @GetMapping("/list")
    public Object list(
            @RequestParam(value = "page",required = false,defaultValue = "1") Integer page,
            @RequestParam(value = "limit",required = false,defaultValue = "10") Integer limit,
            String name,String key,String sort,String order
    ){
        IPage<DtsStorage> iPage = storageService.findPage(page,limit,name,key,sort,order);
        Map<String,Object> data = new HashMap<>();
        data.put("total", iPage.getTotal());
        data.put("items", iPage.getRecords());
        return ResponseUtil.ok(data);
    }

    @PostMapping("/create")
    public Object create(MultipartFile file) throws Exception {
        byte[] bytes = file.getBytes();
        DtsStorage storage = new DtsStorage();
        storage.setName(file.getOriginalFilename());
        storage.setType(file.getContentType());
        storage.setSize((int) file.getSize());
        storage = storageService.save(storage,bytes);
        return ResponseUtil.ok(storage);
    }

    @PostMapping("/update")
    public Object update(@RequestBody DtsStorage storage){
        DtsStorage dtsStorage = null;
        try {
            dtsStorage = storageService.update(storage);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return ResponseUtil.fail(-1, e.getMessage());
        }
        return ResponseUtil.ok(dtsStorage);
    }

    @PostMapping("/delete")
    public Object delete(@RequestBody DtsStorage storage){
        storageService.delete(storage);
        return ResponseUtil.ok();
    }
}
